<template>
<div class="local-dir-tree full-height">
  <div class="dir-tree-head row no-wrap bg-primary text-white">
    <q-icon name="iconfont icontubiao-103 margin-r-10 margin-t-10"></q-icon>
    <span class="head-name">本地</span>
    <q-space></q-space>
    <q-input color="teal" outlined dense bg-color="white" v-model.trim="searchVal"
             placeholder="文件夹路径" style="width: 180px;" @keyup.enter="goDir">
      <template v-slot:prepend>
        <q-btn flat round dense icon="iconfont icontubiao-21" size="11px"></q-btn>
<!--        <q-icon name="iconfont icontubiao-21"></q-icon>-->
      </template>
      <template v-slot:append>
        <q-icon name="close" v-if="searchVal.length > 0" @click="clearSearchVal()" class="cursor-pointer" />
      </template>
    </q-input>
  </div>
  <q-scroll-area :thumb-style="thumbStyle" class="q-pa-sm q-gutter-sm dir-tree">
    <q-tree :nodes="localFolder" node-key="id" ref="localFolderTree" :selected.sync="selected"
            no-nodes-label="暂无数据"
            @lazy-load="getFolderChildList" @update:selected="selectTree" selected-color="primary"/>
  </q-scroll-area>
</div>
</template>

<script>
import { getLocalFolderList, getFolderChildList, fileExist } from 'src/assets/js/file-dir'
export default {
  name: 'local-dir-tree',
  data () {
    return {
      searchVal: '', // 搜索值
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      selected: null, // 树形选中数据
      selectedCopy: null, // 树形选中数据
      localFolder: null // 本地文件列表
    }
  },
  created () {
    this.initInfo()
  },
  methods: {
    initInfo () {
      // 获取桌面C、D、E盘目录列表
      this.localFolder = getLocalFolderList()
      if (this.localFolder.length > 0) {
        this.getFile(this.localFolder[0])
        this.selected = this.localFolder[0].id
        this.selectedCopy = this.selected
      }
    },
    // 获取子级列表
    getFolderChildList ({ node, key, done, fail }) {
      let { dirs, nodes } = getFolderChildList(node)
      this.$emit('getFile', nodes, node)
      done(dirs)
    },
    // 获取文件
    getFile (node) {
      let { dirs, nodes } = getFolderChildList(node)
      this.$emit('getFile', nodes, node)
      node.children = dirs
    },
    // 通过右侧双击文件夹获取子文件夹内容，同时让左侧目录树位于相应的位置
    setExpand (selFiles, dirs) {
      this.selected = selFiles.id
      this.selectedCopy = this.selected
      this.$refs.localFolderTree.setExpanded(selFiles.id, true)
    },
    // 目录树选择
    selectTree (target) {
      if (target === null) {
        this.selected = this.selectedCopy
      } else {
        this.selectedCopy = this.selected
      }
      let selNode = this.$refs.localFolderTree.getNodeByKey(this.selected)
      this.getFile(selNode)
      this.$refs.localFolderTree.setExpanded(this.selected, true)
    },
    // 返回上一级目录
    backParentNode () {
      let selNode = this.$refs.localFolderTree.getNodeByKey(this.selected)
      let paths, parentPaths

      // 判断是否是桌面
      if (selNode.path.indexOf('/Desktop') > -1) {
        let path = selNode.path
        let index = path.indexOf('/Desktop')
        let subPath = path.slice(index + 1, path.length)
        paths = subPath.split('/')
        parentPaths = paths.slice(0, paths.length - 2)
      } else {
        paths = selNode.path.split('/')
        parentPaths = paths.slice(0, paths.length - 2)
      }
      const parentNode = this.getParentNode(parentPaths, this.localFolder, 0)
      this.selected = parentNode.id
      this.selectedCopy = this.selected
      this.$refs.localFolderTree.setExpanded(this.selected, true)
      this.getFile(parentNode)
    },
    // 获取父级node
    getParentNode (parentPaths, nodes, level) {
      let result = nodes.find(item => {
        return (item._name && item._name === parentPaths[level]) || item.label === parentPaths[level]
      })
      if (parentPaths.length - 1 !== level) {
        result = this.getParentNode(parentPaths, result.children, level + 1)
      }
      return result
    },
    // 根据搜索值跳转路径
    goDir () {
      let searchVal = this.searchVal
      if (!fileExist(this.searchVal)) {
        this.errMessage('目录' + this.searchVal + '不存在')
        return
      }
      if (this.searchVal[this.searchVal.length - 1] !== '/' && this.searchVal[this.searchVal.length - 1] !== '\\') {
        searchVal = searchVal + '/'
      }
      let paths = searchVal.replace(/\\/g, '/').split('/')
      if (paths[paths.length - 1] === '') {
        paths.pop()
      }
      let curNode = {
        children: this.localFolder
      }
      paths.forEach((item, index) => {
        let path = paths.slice(0, index + 1).join('/') + '/'
        let node = {
          path,
          label: item
        }
        let { dirs, nodes } = getFolderChildList(node)
        if (!curNode) {
          this.errMessage('目录' + path + '读取失败')
          return
        }
        curNode = curNode.children.find(item => {
          return item.path === path
        })
        if (!curNode) {
          this.errMessage('目录' + path + '读取失败')
          return
        }
        curNode.children = dirs
        this.selected = curNode.id
        this.$refs.localFolderTree.setExpanded(curNode.id, true)
        let selNode = this.$refs.localFolderTree.getNodeByKey(this.selected)
        console.log(selNode)
        if (index === paths.length - 1) {
          this.selected = curNode.id
          this.selectedCopy = this.selected
          // this.$refs.localFolderTree.setExpanded(curNode.id, true)
          this.$emit('getFile', nodes, curNode)
        }
      })
      this.selectedCopy = this.selected
    },
    // 清空搜索值
    clearSearchVal () {
      this.searchVal = ''
    },
    // 失败提示
    errMessage (message) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-52" ></i> 提示</p>`,
        message: message,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.dir-tree-head{
  padding 0 20px
  height 40px
  line-height 40px
  font-size 18px
}
.dir-tree{
  height calc(100% - 40px)
}
</style>
